//JavaScript代码区域
layui.use('element', function(){
  var element = layui.element;
  
});
layui.use(['laytpl','table','layer'], function(){
  var laytpl = layui.laytpl;
  var table = layui.table;
  var layer = layui.layer;
  var $ = layui.$;
  function checkEmail(email) {

	// 对电子邮件的验证

	var myreg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;

	if (!myreg.test(email)) {

	return false;

	} else {

	return true;

	}
  }
function initData(id,data,getTpl){
		view = document.getElementById(id);
		laytpl(getTpl).render(data, function(html){
		  view.innerHTML = html;
		});
	}
  var user = layui.sessionData('user');
	if(user == null || user == undefined ||$.isEmptyObject(user) || user.data.id!=1){
		window.location.href = "./login.html"
	}
	var getTpl = person.innerHTML
	initData('account',user,getTpl);
  var articleTHead = [
	  {type: 'checkbox', fixed: 'left'}
  ,{field:'id',title:'ID', width:'6%',type:'numbers',sort: true, fixed: 'left'}
  , {field:'title',title:'标题', width:'20%', fixed: 'center'}
  , {field:'content',title:'内容', width:'40%', fixed: 'center'}
  , {field:'ctime',title:'创建日期', width:'15%',sort: true, fixed: 'left'}
  , {field:'do',title:'操作',toolbar: '#articleBar'}
  ]

  var categoryTHead = [
	  {type: 'checkbox', fixed: 'left'}
   ,{field:'id',title:'ID', width:'6%',type:'numbers',sort: true, fixed: 'left'}
  , {field:'content',title:'类别', width:'20%', fixed: 'center'}
  , {field:'ctime',title:'创建日期', width:'20%',sort: true, fixed: 'left'}
  , {field:'do',title:'操作',toolbar: '#otherBar'}
  ]

  var labelTHead = [  
  {type: 'checkbox', fixed: 'left'}
  ,{field:'id',title:'ID', width:'6%',type:'numbers',sort: true, fixed: 'left'}
  , {field:'content',title:'标签', width:'20%', fixed: 'center'}
  , {field:'ctime',title:'创建日期', width:'20%',sort: true, fixed: 'left'}
  , {field:'do',title:'操作',toolbar: '#otherBar'}
  ]

	var discussTHead = [
		{type: 'checkbox', fixed: 'left'}
	  ,{field:'id',title:'ID', width:'6%',type:'numbers',sort: true, fixed: 'left'}
	  , {field:'content',title:'评论内容', width:'30%', fixed: 'left'}
	  , {field:'articleId',title:'文章标题', width:'10%', fixed: 'left'}
	  , {field:'discusser',title:'评论者', width:'15%', fixed: 'left'}
	  , {field:'ctime',title:'创建日期', width:'20%',sort: true, fixed: 'left'}
	  , {field:'do',title:'操作',toolbar: '#otherBar'}
	  ]

	var userTHead = [
		{type: 'checkbox', fixed: 'left'}
	  ,{field:'id',title:'ID', width:'6%',type:'numbers',sort: true, fixed: 'left'}
	  , {field:'acount',title:'账号', width:'10%', fixed: 'center'}
	  , {field:'name',title:'用户名', width:'15%', fixed: 'center'}
	  , {field:'email',title:'邮箱', width:'20%', fixed: 'center'}
	  , {field:'ctime',title:'创建日期', width:'20%',sort: true, fixed: 'left'}
	  , {field:'do',title:'操作',toolbar: '#userBar'}
	  ]
  
	var tableHeadr = [articleTHead,categoryTHead,labelTHead,discussTHead,userTHead]
	var target = [
	'article/article'
	,'category/categoryType'
	,'label/labelType'
	,'discuss/discuss'
	,'user/user'
	]
  	var menuIndex = layui.sessionData('menu').id;
	window.showTableData = function(id=0){
		console.log(parseInt(id));
		var data = tableHeadr[id]
		layui.sessionData('menu',{
			key:'id'
			,value: id
		})
		console.log(layui.sessionData('menu').id);	
	  table.render({
		elem: '#demo'
		,height: 480
		,url: '/blog/'+target[id]+ 'List' //数据接口
		,toolbar: '#toolBar' 
		,page: true //开启分页
		,cols: [data]
		,response: {
			  statusCode: 200
			}
		,parseData: function(res){ //res 即为原始返回的数据
			console.log(res.code)
			console.log(res.msg)
			if(res.data!=null){
				console.log(res.data.data.length)
				console.log(res.data.data)
				var code = res.code
				,msg = res.msg
				,da = res.data.data.list
				,count = res.data.data.total
				return {
				  "code": code, //解析接口状态
				  "msg": msg, //解析提示文本
				  "count": count, //解析数据长度
				  "data": da //解析数据列表
				}
			}else{
				return {
					  "code": 200, //解析接口状态
					  "msg": "无数据", //解析提示文本
					  "count": 0, //解析数据长度
					  "data": [] //解析数据列表
					}
			}
			
		}
		
	  });
	  if(id==0 || id == 3){
		  $('#addItem').addClass('layui-hide')
	  }
	}
  if(menuIndex == undefined){
	  menuIndex= 0
  }
  showTableData(menuIndex);
	 $('#logout').on('click',function(){
     	layui.sessionData('user',{
     		key:'data',
     		remove: true
     	})
     	layer.msg("注销成功！")
     	window.location.href="./index.html"
     })
  	//showTableDate(0);
	//头工具栏事件
    table.on('toolbar(demo)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var menuIndex = layui.sessionData('menu').id;
        switch (obj.event) {
            case 'getCheckData':
                var data = checkStatus.data;
                layer.alert(JSON.stringify(data));
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
            case 'add':
            	console.log("添加成功")
            	if(menuIndex==4){
            		//window.location.href="./login.html";
            		var usr = {};
            		 layer.open({
                         type: 1 //Page层类型
                         ,fixed: false
                         ,skin: 'layui-layer-molv'
                         ,area: ['500px', '300px']
                         ,title: ['新建用户信息','font-size:18px']
                         ,btn: ['确定', '取消'] 
                         ,shadeClose: true
                         ,shade: 0 //遮罩透明度
                         ,maxmin: true //允许全屏最小化
                         ,content:$("#window")  //弹窗路径
                         ,success:function(layero,index){
                        	 usr.name = $('#name').val();
                        	 usr.email = $('#email').val(); 
                        	 usr.password = $('#password').val();  
                         },yes:function(index,layero){
                        	 var name = $('#name').val();
                        	 var email = $('#email').val();
                        	 var password = $('#password').val();
                        	 if(!checkEmail(email)){
                        		 layer.msg('邮箱格式有误！')
                        		 return false;
                        	 }
                        	 var item = {
                        			 'name':  name
                        			 ,'email': email
                        			 ,'password': password
                        	 }
                        	 $.ajax({
                                 url: "/blog/"+target[menuIndex],    //换成自己的url
                                 type: "POST",
                     	         contentType:"application/json;charset=utf-8",
                                 dataType: "json",
                                 data: JSON.stringify(item),
                                 success: function (e) {
                                     if (e.code == 200) {
                                         layer.msg("添加成功");
                                         window.location.reload();
                                     } else {
                                         layer.msg("添加失败");
                                     }
                                 },
                                 fail: function (e) {
                                     layer.msg(e);
                                 }
                             })
                                
                         }
                     });
            	}else{
            		var title = ['类别','标签']
                	layer.prompt({
                	  formType: 0,
                	  value: '',
                	  title: '请输新的'+title[menuIndex-1],
                	}, function(value, index, elem){
                		console.log('value:'+value+'，index:'+index+'，elem:'+elem)
                	  layer.close(index);
                  	  var item = {
                			  'content': value
                	  };
                	  //修改
                      $.ajax({
                          type: "POST",
                          url: "http://127.0.0.1:8080/blog/"+target[menuIndex],
                          dataType: "json",
                          contentType : 'application/json;charset=utf-8',//重要
                          data: JSON.stringify(item),
                          success: function (data) {
                          	if(data.code==200){
                          		window.location.reload();
                          	}
                          	console.log(rs)
                          	window.location.reload();
                          }
                      })
                	});
            	}
                break;
            case 'batchDel':
            	var ids = [];
            	layui.each(checkStatus.data,function(index,item){
            		ids.push(item.id);
            	})
            	console.log("ids:"+ids)
            	console.log("批量删除成功")
                /*发送ajax请求到后台执行批量删除*/
            	$.ajax({
                    type: "DELETE",
                    url: "http://127.0.0.1:8080/blog/"+target[menuIndex],
                    dataType: "json",
                    contentType : 'application/json;charset=utf-8',//重要
                    data: JSON.stringify(ids),
                    success: function (data) {
                    	if(data.code==200){
                    		window.location.reload();
                    	}
                    	console.log(rs)
                    	window.location.reload();
                    }
                });
                break;
            case 'flush':
            	console.log("刷新成功")
                showTableData(index);
                break;
            case 'search':
            	console.log("查找成功")
                layer.msg("根据关键词查找");
                var keyword = $('input[name="search"]').val();
                table.reload('demo',{
            		//elem: '#demo',
            		//height: 480,
                    url: "/blog/"+target[menuIndex]+"List",    //换成自己的url
                    where: {
                        "keyword": keyword,
                    },
            			toolbar: '#toolBar' 
            			,page: true //开启分页
            			,cols: [data]
            			,response: {
            				  statusCode: 200
            				}
            			,parseData: function(res){ //res 即为原始返回的数据
            				console.log(res.code)
            				console.log(res.msg)
            				console.log(res.data.data.length)
            				console.log(res.data.data)
            				var code = res.code
            				,msg = res.msg
            				,da = res.data.data.list
            				,count = res.data.data.total
            				return {
            				  "code": code, //解析接口状态
            				  "msg": msg, //解析提示文本
            				  "count": count, //解析数据长度
            				  "data": da //解析数据列表
            				}
            			}
            			
            		  });
                break;
        }
        ;
    });
    //监听行工具事件
    table.on('tool(demo)', function (obj) {
        var data = obj.data
        , menuIndex = layui.sessionData('menu').id
        , key =obj.event;
        switch(key){
        case 'del':
        {
        	console.log("删除成功")
            layer.confirm('确定删除', function (index) {
                obj.del();
                layer.close(index);
                //删除
                $.ajax({
                    type: "DELETE",
                    url: "http://127.0.0.1:8080/blog/"+target[menuIndex]+"/"+data.id,
                    dataType: "json",
                    contentType : 'application/json;charset=utf-8',//重要
                    success: function (data) {
                    	if(data.code==200){
                    		window.location.reload();
                    	}
                    	console.log(data)
                    	layer.msg(data.msg)
                    	window.location.reload();
                    }
                });
            });
        }
        	break;
        case 'detail':
        {
        	console.log("查看成功")
        	window.location.href="/blog/blogg/article.html?id="+obj.data.id
        }
        	break;
        case 'update':
        {
        	console.log("修改成功")
        	var title = ['类别','标签','评论内容']
        	layer.prompt({
        	  formType: 0,
        	  value: data.content,
        	  title: title[menuIndex-1],
        	}, function(value, index, elem){
        		console.log('value:'+value+'，index:'+index+'，elem:'+elem)
        	  layer.close(index);
        	  var item = {
        			  'id': data.id
        			  ,'content': value
        	  };
        	  //修改
              $.ajax({
                  type: "PUT",
                  url: "http://127.0.0.1:8080/blog/"+target[menuIndex],
                  dataType: "json",
                  contentType : 'application/json;charset=utf-8',//重要
                  data: JSON.stringify(item),
                  success: function (data) {
                  	if(data.code==200){
                  		window.location.reload();
                  	}
                  	console.log(rs)
                  	window.location.reload();
                  }
              })
        	});
        }
        	break;
        case 'resetPwd':
        {
        	console.log("重置密码成功")
        	//修改
            $.ajax({
                type: "PUT",
                url: "http://127.0.0.1:8080/blog/user/resetPassword/"+data.id,
                dataType: "json",
                contentType : 'application/json;charset=utf-8',//重要
                success: function (data) {
                	if(data.code==200){
                		window.location.reload();
                	}
                	console.log(rs)
                	window.location.reload();
                }
            })
        }        	
        	break;
        }
    });
});